package com.gykfbxxh.imovie.view.main.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.volley.VolleyError;
import com.app.utils.util.LogUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.AppApplication;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.adapter.FilmsListAdapter;
import com.gykfbxxh.imovie.adapter.pageAdapter.NewsPicPagerAdapter;
import com.gykfbxxh.imovie.base.BaseListFragment;
import com.gykfbxxh.imovie.bean.film.FilmEntity;
import com.gykfbxxh.imovie.bean.film.FilmListBean;
import com.gykfbxxh.imovie.bean.film.FilmListEntity;
import com.gykfbxxh.imovie.bean.news.FilmBannerBean;
import com.gykfbxxh.imovie.config.TypeConstant;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.custom.view.MyViewPager;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.utils.AnimationUtils;
import com.gykfbxxh.imovie.utils.HttpUtils;
import com.gykfbxxh.imovie.utils.glide.ImageLoader;
import com.gykfbxxh.imovie.videoplayer.JCMediaManager;
import com.gykfbxxh.imovie.videoplayer.JCVideoPlayer;
import com.gykfbxxh.imovie.videoplayer.JCVideoPlayerManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xuxinghai
 * On 2017/8/25
 * 电影fragment
 */

public class FilmsListFragment extends BaseListFragment<FilmListEntity> {
    /*********
     * 逻辑数据
     **********/
    private String mChannelId;//栏目id
    private String mChannelName;//栏目名称
    private int mChannelType;//栏目类型
    private boolean isFocus;//是否是聚焦栏目
    private Activity mActivity;
    private ViewGroup mContentView;//根布局

    private boolean isStop;//listView是否停止
    private int mMark;//下拉刷新请求标识

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();

        mChannelId = (args != null ? args.getString("id", "0") : "0");
        mChannelName = (args != null ? args.getString("name", "null") : "null");
        mChannelType = (args != null ? args.getInt("type", 1) : 1);
        isFocus = (args != null && !TextUtils.isEmpty(args.getString("focus_news")));

    }


    @Override
    public void onAttach(Activity activity) {
        mActivity = activity;
        super.onAttach(activity);
    }

    @Override
    public void onPause() {
        super.onPause();
//        NiceVideoPlayerManager.instance().releaseNiceVideoPlayer();
        AnimationUtils.getInstance().stopLooperTimer();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void changeData(final boolean isRefresh) {
        HttpUtils.addGetRequest(URIContant.FILMLIST+dataPage, new TypeToken<FilmListBean>() {
        }.getType(), mPageName, new HttpListener<FilmListBean>() {

            @Override
            public void onStart() {
                setLoadView(LOADING, null);
            }

            @Override
            public void onError(VolleyError error) {
                setLoadView(NO_NET, AppApplication.getInstance().getString(R.string.neterror));
            }

            @Override
            public void onSuccess(FilmListBean response) {
                LogUtils.e("xuxh", "onSuccess");
                if (response != null && response.getResult() != null) {
                    FilmListBean.ResultBean result = response.getResult();
                    if (result != null) {
                        List<FilmListEntity> list = result.getList();
                        if (list != null && list.size() > 0) {
                            if (dataList == null) {
                                dataList = new ArrayList<FilmListEntity>();
                            }
                            //异常数据处理
                            dataRevisited(list, (isRefresh && mMark == 0));
                            if (isRefresh) {
                                if (1 == mChannelType) {
                                    initHeadData();//刷新头部轮播
                                }
                                dataList.clear();
                            }
                            dataList.addAll(list);
                            if (mAdapter == null) {
                                mAdapter = new FilmsListAdapter(dataList, activity, mChannelType);
                                mListView.setAdapter(mAdapter);
                            } else {
                                mAdapter.notifyDataSetChanged();
                            }
                            if (isRefresh) {
                                if (list.size() > 1) {
                                    String msg = "推荐引擎有<font color='#F9D13F'>" + (list.size() ) + "</font>条新数据";
                                    setLoadView(LOADSUCES, Html.fromHtml(msg));
                                } else {
                                    //updateLoadView(LOADSUCES, "暂无新数据");
                                    setLoadView(LOADSUCES, getString(R.string.pullup_nomore_data));
                                }
                            } else {
                                setLoadView(LOADSUCES, "");
                            }

                        } else {
                            setLoadView(LOADSUCES, getString(R.string.pullup_nomore_data));
                        }
                    } else {
                        setLoadView(DATAERROR, response.getErrorMsg());
                    }
                } else {
                    setLoadView(DATAERROR, response.getErrorMsg());
                }
            }
        });
    }

    private View picView;//头部轮播图
    private Handler picHanfler;//自动轮播图片操作
    private Timer timer;//自动轮播计时

    private void initHeadData(){
        HttpUtils.addGetRequest(URIContant.GETBANNER, new TypeToken<FilmBannerBean>() {
        }.getType(), mPageName, new HttpListener<FilmBannerBean>() {
            @Override
            public void onError(VolleyError error) {
                //如果是刷新则移除轮播图
                if (mListView.getRefreshableView().getHeaderViewsCount() > 1 && picView != null) {
                    //添加之前先移除原有的头部
                    mListView.getRefreshableView().removeHeaderView(picView);
                    picView = null;
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                }
            }

            @Override
            public void onSuccess(FilmBannerBean result) {
                if (result!=null&&result.getResult()!=null && result.getResult().getList()!=null&& result.getResult().getList().size()>0){
                    List<FilmEntity> bannerList = result.getResult().getList();
                    adapterHeadData(bannerList);
                    if(dataList!=null&&dataList.size()>0) {
                        dataList.get(0).setPicsList(bannerList);
                        mAdapter.notifyDataSetChanged();
                        mListView.onRefreshComplete();
                    }

                }else {
                    //如果是刷新则移除轮播图
                    if (mListView.getRefreshableView().getHeaderViewsCount() > 1 && picView != null) {
                        //添加之前先移除原有的头部
                        mListView.getRefreshableView().removeHeaderView(picView);
                        picView = null;
                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                        }
                    }
                }
            }
        });
    }
    /**
     * 设置头部轮播图
     */
    private void adapterHeadData(List<FilmEntity> picsList) {

        //如果是刷新则移除轮播图
        if (mListView.getRefreshableView().getHeaderViewsCount() > 1 && picView != null) {
            //添加之前先移除原有的头部
            mListView.getRefreshableView().removeHeaderView(picView);
            picView = null;
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
        }

        picView = activity.getLayoutInflater().inflate(R.layout.news_list_header, null);
        ViewGroup iconsView = (ViewGroup) picView.findViewById(android.R.id.widget_frame);
        final MyViewPager picViewPager = (MyViewPager) picView.findViewById(R.id.newsPic_ViewPager);
        if (picsList != null && picsList.size() > 0) {
            ArrayList<View> bigImgs = new ArrayList<View>();
            for (int i = 0; i < picsList.size(); i++) {

                if (i == 0) {
                    ImageView imageView = new ImageView(activity);
                    imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.setTag(R.id.tag_first, picsList.get(picsList.size() - 1));
                    FilmEntity newsEntity = picsList.get(picsList.size() - 1);
                    if (!TextUtils.isEmpty(newsEntity.getFPhotow())) {
                        ImageLoader.getInstance().loadImage1zhi(mActivity,imageView, newsEntity.getFPhotow());
                    }
//                    imageView.setImageURI(picsList.get(picsList.size() - 1).getImg());
                    bigImgs.add(imageView);
                }

                ImageView imageView = new ImageView(activity);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                imageView.setTag(R.id.tag_first, picsList.get(i));
                imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                FilmEntity newsEntity = picsList.get(i);
                if (!TextUtils.isEmpty(newsEntity.getFPhotow())) {
                    ImageLoader.getInstance().loadImage1zhi(mActivity,imageView, newsEntity.getFPhotow());
                }
                bigImgs.add(imageView);
                ImageView imageView1 = new ImageView(activity);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                imageView1.setLayoutParams(layoutParams);
                imageView1.setImageResource(R.drawable.drop_2);
                iconsView.addView(imageView1);
            }
            ImageView imageView = new ImageView(activity);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setTag(R.id.tag_first, picsList.get(0));
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            FilmEntity newsEntity = picsList.get(0);
            if (!TextUtils.isEmpty(newsEntity.getFPhotow())) {
                ImageLoader.getInstance().loadImage1zhi(mActivity,imageView, newsEntity.getFPhotow());
            }
            bigImgs.add(imageView);

            final NewsPicPagerAdapter adapter = new NewsPicPagerAdapter(bigImgs, iconsView, picsList, activity, picViewPager);
            picViewPager.setAdapter(adapter);
            picViewPager.setCurrentItem(1);
            picViewPager.setOnPageChangeListener(adapter);
            ((ImageView) iconsView.getChildAt(0)).setImageResource(R.drawable.drop_1);
            ((ImageView) iconsView.getChildAt(0)).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            ViewSizeUtils.changeScreenW_H(picViewPager, 0.50f);
            //轮播图自动滚动
            picHanfler = new Handler() {
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case 0:
                            if (picViewPager.getCurrentItem() == adapter.getCount() - 1) {
                                picViewPager.setCurrentItem(0);
                            } else {
                                picViewPager.setCurrentItem(picViewPager.getCurrentItem() + 1);
                            }
                            break;
                    }
                }
            };
            timer = new Timer(true);
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    picHanfler.sendEmptyMessage(0);
                }
            }, 5000, 5000);
        }
        mListView.getRefreshableView().addHeaderView(picView);
        mListView.onRefreshComplete();
    }

    /**
     * 去除无效数据
     *
     * @param list
     * @param b
     */
    private void dataRevisited(List<FilmListEntity> list, boolean b) {
        if (list == null || list.size() == 0) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            if (i >= list.size()) {
                break;
            }
            FilmListEntity listBean = list.get(i);
            if (listBean == null) {
                continue;
            }
            if (TextUtils.isEmpty(listBean.getFObject().getFSourceurl())) {
                list.remove(i);
                i--;
                continue;
            }

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //因为有头部
        if (mListView.getRefreshableView().getHeaderViewsCount() > 0) {
            position = position - mListView.getRefreshableView().getHeaderViewsCount();
        }
        //防止越界
        if (position >= dataList.size()) {
            position = dataList.size() - 1;
        } else if (position < 0) {
            position = 0;
        }
        FilmListEntity filmListEntity = dataList.get(position);

        TypeConstant.openTypeDetail(filmListEntity.getFObject(), activity, TypeConstant.SOURCETYPE_NORMAL) ;

    }

    /**
     * LoadViewd 方法
     *
     * @param code 传入对应的值
     * @param msg  提示的的文字
     */
    protected void setLoadView(int code, CharSequence msg) {

        switch (code) {
            case NO_NET://网络错误
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showErrorPage(msg);
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                        }
                    }, 800);
                }
                break;
            case DATAERROR://数据错误
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showErrorPage(msg);
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                        }
                    }, 800);
                }
                break;
            case LOADING://加载中
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showLoadPage(msg);
                }
                break;
            case LOADSUCES://加载成功
                if (dataList != null && dataList.size() > 0) {
                    mLoadView.showSuccess();
                } else {
                    mLoadView.showEmptyPage(TypeConstant.EMPTY_DEFAULT, "");
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                        }
                    }, 800);
                }
                break;
        }
        if (msg != null && !"".equals(msg)) {
            notify_view_text.setText(msg);
            notify_view_text.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    notify_view_text.setVisibility(View.GONE);
                }
            }, 2000);
        }
    }

    @Override
    protected void changeView() {
        mListView.getRefreshableView().setOnScrollListener(new AbsListView.OnScrollListener() {

            int firstPosition = 1;//上一次的第一个位置
            int lastPosition;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (isStop && !mListView.isRefreshing()) {
//                        isStop=false;
                        mListView.showFootView();
//				mListView.getRefreshableView().setSelection(newsList.size());
                        onPullUpToRefresh(mListView);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

//                LogUtils.e("xuxh","firstVisibleItem"+firstVisibleItem);
//                LogUtils.e("xuxh","visibleItemCount=" + visibleItemCount);
//                LogUtils.e("xuxh","totalItemCount"+totalItemCount);

                if (JCVideoPlayer.IS_FULLSCREEN) {
                    return;
                }
                if ((totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount)) {
                    isStop = true;
                } else {
                    isStop = false;
                }
                //如果当前有视频播放则判断滑动屏幕时是否暂停视频
                if (JCMediaManager.isUseing) {
                    if (firstPosition < firstVisibleItem) {
                        //说明手指往上滑
                        if (mAdapter != null) {
                            if(firstVisibleItem<2) {
                                return;
                            }
                            int pos = 0;
                            if (firstPosition > 0) {
//                                pos = firstPosition - 1;
                                pos = firstPosition - mListView.getRefreshableView().getHeaderViewsCount();
                            }
                            if(pos<0) {
                                pos = 0;
                            }
                            String fSourceurl = ((FilmListEntity) mAdapter.getItem(pos)).getFObject().getFSourceurl();
                            if (!TextUtils.isEmpty(fSourceurl) && !TextUtils.isEmpty(JCVideoPlayerManager.PLAYING_URL) && fSourceurl.equals(JCVideoPlayerManager.PLAYING_URL)) {
                                //如果滚出屏幕的是视频稿子则 停止播放器
                                JCVideoPlayer.releaseAllVideos();
                            }
                        }

                        firstPosition = firstVisibleItem;

                    } else if (lastPosition > (firstVisibleItem + visibleItemCount - 1)) {
                        //说明手指往下滑
                        String fSourceurl = null;
                        try {
                            fSourceurl = ((FilmListEntity) mAdapter.getItem(lastPosition- mListView.getRefreshableView().getHeaderViewsCount() )).getFObject().getFSourceurl();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (!TextUtils.isEmpty(fSourceurl) && !TextUtils.isEmpty(JCVideoPlayerManager.PLAYING_URL) && fSourceurl.equals(JCVideoPlayerManager.PLAYING_URL)) {
                            //如果滚出屏幕的是视频稿子则 停止播放器
                            JCVideoPlayer.releaseAllVideos();
                        }
                        firstPosition = firstVisibleItem;
                    }
                    lastPosition = firstVisibleItem + visibleItemCount - 1;
                }

            }
        });
    }

    /**
     * 刷新 downview
     */
    public void notifyDown() {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void startActivity(Intent intent) {
        if (activity != null) {
            activity.startActivity(intent);
        } else {
            super.startActivity(intent);
        }
    }

    private View.OnClickListener onClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_like:
                    FilmEntity filmEntity = (FilmEntity) v.getTag(R.id.tag_first);
                    ToastUtils.makeText("点击了" + filmEntity.getFName() + "喜欢");
                    break;
                case R.id.ll_share:
                    FilmEntity filmEntity1 = (FilmEntity) v.getTag(R.id.tag_first);
                    ToastUtils.makeText("点击了" + filmEntity1.getFName() + "分享");
                    break;
                case R.id.ll_more:
                    FilmEntity filmEntity2 = (FilmEntity) v.getTag(R.id.tag_first);
                    ToastUtils.makeText("点击了" + filmEntity2.getFName() + "更多");
                    break;
            }
        }
    };

}
